<?php

namespace app\api\controller\v48;

use app\api\controller\v2\Auth;
use app\common\cachemodel\AppSynastryResult;
use app\common\cachemodel\Recode;
use app\common\cachemodel\zl2\Zl2FamousPersonRecode;
use app\common\cachemodel\ZlStarRecode;
use app\common\cachemodel\ZlSynastryReport;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\astrolog\SynastryData;
use app\common\lib\SensorsData;
use app\common\lib\Util;
use think\Env;
use think\response\Json;

class Synastry extends Auth
{
    /**
     * 合盘记录
     */
    public function getHistoryList()
    {
        $page = input('page/d', 1);

        $uid = (int)$this->user['id'];

        $data = (new AppSynastryResult())->getUserList2($uid, $page);

        $data['vip_level'] = (new ZlUserVip())->getUserVipLevel($uid);

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 获取合盘结果
     * @return Json
     * @throws \think\Exception
     */
    public function getWithScore()
    {
        $id = input('id/d', 0);
        $type = input('type/d', 0);
        $rid1 = input('rid1/d', 0);
        $rid2 = input('rid2/d', 0);
        $uid = (int)$this->user['id'];
        $sType = 1; //合盘类型 1=>普通合盘 2=>明星合盘 5=>名人合盘
        #神策打点 25 合盘操作 SynastryHandle
        $sensorsTrackData = [
            'synastry_score' => 0,//  合盘得分
            'record1_name' => '',// 合盘左边档案名称
            'record1_id' => $rid1,// 合盘左边档案ID
            'record2_name' => '',// 合盘右边档案名称
            'record2_id' => $rid2,// 合盘右边档案ID
            'has_self' => false,// 是否含有自己的档案
            'is_success' => true,// 是否成功
            'failed_reson' => '',// 失败原因
        ];
        $distinctId = $this->request->header('distinct-id', '');
        if (!in_array($type, [1, 2, 3, 5, 7, 8, 9, 10, 11], true) || ($type === 1 && !$id) || ($type !== 1 && (!$rid1 || !$rid2)))
        {
            if ($distinctId)
            {
                $sensorsTrackData['is_success'] = false;
                $sensorsTrackData['failed_reson'] = '请求参数异常';
                SensorsData::track($uid, true, 'SynastryHandle', $sensorsTrackData);
            }
            return show(config('code.error'), '请求异常');
        }
        $recodeModel = new Recode();
        $saveData = [];
        if ($type === 1)
        {   // 通过id查询
            $result = (new AppSynastryResult())->getInfoById($id);
            if ($result['uid'] != $uid)
            {
                if ($distinctId)
                {
                    $sensorsTrackData['is_success'] = false;
                    $sensorsTrackData['failed_reson'] = '数据不存在';
                    SensorsData::track($uid, true, 'SynastryHandle', $sensorsTrackData);
                }
                return show(config('code.error'), '数据不存在');
            }
            if (isset($result['type']))
            {   // 合盘类型 1=>普通合盘 2=>明星合盘 3=>有档案被删除  4=>活动邀请合盘未创建档案 5=>名人合盘 6=>邀请好友填档案合盘（不添加档案）
                $sType = (int)$result['type'];
            }
            $recordDatas = json_decode($result['extra'], true);
            $rid1 = (int)$result['rid1'];
            $rid2 = (int)$result['rid2'];
            // 获取完整合盘数据
            $recordDatas['type'] = 1;
            if (!in_array($sType, [5, 6], true) && (!$rid1 || !$rid2))
            {
                $sType = 2;
            }
            $synastryType = $result['synastry_type'] ?? 0;
            if (!$synastryType)
            {   // 旧 合盘 逻辑
                $synastryType = $result['type'] == 5 ? 5 : 2;
            }
        } else
        {
            $record1 = $recodeModel->getInfoById($rid1, ['id', 'uid', 'name', 'type', 'year', 'month', 'day', 'hour', 'minute', 'timezone', 'long_deg', 'long_min', 'ew', 'lat_deg', 'lat_min', 'ns', 'avatar', 'is_summer', 'isself', 'sun', 'moon', 'asc']);
            if (!$record1 || $record1['uid'] != $uid)
            {
                return show(config('code.error'), '档案缺失');
            }
            if ($record1['isself'] == 1)
            {
                $record1['name_old'] = $record1['name'];
                $record1['name'] = '自己';
            }

            switch ($type)
            {
                case 3: // 明星合盘
                    $sType = 2;// 明星合盘
                    $recodeData = (new ZlStarRecode())->getInfoById($rid2);
                    if (!$recodeData)
                    {
                        return show(config('code.error'), '档案缺失');
                    }
                    $record2 = json_decode($recodeData['extra'], true);
                    break;
                case 5:// 名人合盘
                    $sType = 5;// 名人合盘
                    $recodeData = (new Zl2FamousPersonRecode())->getInfoById($rid2);
                    if (!$recodeData)
                    {
                        return show(config('code.error'), '档案缺失');
                    }
                    $record2 = $recodeData['extra'];
                    break;
                default:// 普通合盘
                    $record2 = $recodeModel->getInfoById($rid2, ['id', 'uid', 'name', 'type', 'year', 'month', 'day', 'hour', 'minute', 'timezone', 'long_deg', 'long_min', 'ew', 'lat_deg', 'lat_min', 'ns', 'avatar', 'is_summer', 'isself']);
                    if (!$record2 || $record2['uid'] != $uid)
                    {
                        if ($distinctId)
                        {
                            $sensorsTrackData['is_success'] = false;
                            $sensorsTrackData['failed_reson'] = '档案不存在或不属于本人';
                            SensorsData::track($uid, true, 'SynastryHandle', $sensorsTrackData);
                        }
                        return show(config('code.error'), '档案缺失');
                    }
                    if ($record2['isself'] == 1)
                    {
                        $record2['name'] = '自己';
                    }
            }
            $synastryType = $type;
            $recordDatas = [
                'recode1' => $record1,
                'recode2' => $record2,
                'type' => 1,
            ];
            //rid处理确保入库唯一性
            if ($rid2 > $rid1)
            {
                $newRid1 = $rid2;
                $newRid2 = $rid1;
            } else
            {
                $newRid1 = $rid1;
                $newRid2 = $rid2;
            }
            $saveData = [ // 合盘记录表
                'uid' => $uid,
                'type' => $sType,
                'synastry_type' => in_array($type, [7, 8, 9, 10, 11]) ? $type : 0,
                'create_type' => 2,
                'rid1' => $newRid1,
                'rid2' => $newRid2,
                'create_time' => $this->request->time(),
                'update_time' => $this->request->time(),
                'nickname1' => $record1['name'],
                'nickname2' => $record2['name'],
                'avatar1' => $record1['avatar'] ?: '',
                'avatar2' => $record2['avatar'] ?: '',
                'extra' => json_encode([
                    'recode1' => $record1,
                    'recode2' => $record2,
                ]),
            ];
        }
        $synastryType = (int)$synastryType;
        $data = (new SynastryData())->setSynastryType($synastryType)->getScore($recordDatas);
        foreach ($data['score'] as $k => $item)
        {
            $data['score'][$k]['num'] = (int)$item['num'];
        }
        $scoreComment = [];
        if (in_array($synastryType, [7, 8, 9, 10, 11], false))
        {   // 新 合盘类型 7=>大众合盘 8=>恋爱合盘  9=>婚姻合盘 10=>事业合盘  11=>朋友合盘
            $synastryService = new \app\common\lib\astrolog\Synastry();
            $newData = $synastryService->getData2024($recordDatas['recode1'], $recordDatas['recode2'], $synastryType);
            if (in_array($synastryType, [8, 9, 10, 11]))
            {
                $data['score']['attract'] = [
                    'num' => min((int)ceil(($newData[0]['score'] ?? 0) * $synastryService->multiple), 95),
                    'name' => $newData[0]['name'] ?? '',
                    'text' => $newData[0]['text'] ?? '',
                ];
                $data['score']['benefit'] = [
                    'num' => min((int)ceil(($newData[1]['score'] ?? 0) * $synastryService->multiple), 95),
                    'name' => $newData[1]['name'] ?? '',
                    'text' => $newData[1]['text'] ?? '',
                ];
                $data['score']['chat'] = [
                    'num' => min((int)ceil(($newData[2]['score'] ?? 0) * $synastryService->multiple), 95),
                    'name' => $newData[2]['name'] ?? '',
                    'text' => $newData[2]['text'] ?? '',
                ];
                $data['score']['happy'] = [
                    'num' => min((int)ceil(($newData[3]['score'] ?? 0) * $synastryService->multiple), 95),
                    'name' => $newData[3]['name'] ?? '',
                    'text' => $newData[3]['text'] ?? '',
                ];
                $data['score']['passion'] = [
                    'num' => min((int)ceil(($newData[4]['score'] ?? 0) * $synastryService->multiple), 95),
                    'name' => $newData[4]['name'] ?? '',
                    'text' => $newData[4]['text'] ?? '',
                ];
                $data['score']['probTobeLover'] = [
                    'num' => min((int)ceil(($newData[5]['score'] ?? 0) * $synastryService->multiple), 95),
                    'name' => $newData[5]['name'] ?? '',
                    'text' => $newData[5]['text'] ?? '',
                ];

                $summaryComparisonTitle = [
                    8 => '恋爱关系主导',
                    9 => '婚姻付出比较',
                    10 => '合作压力比较',
                    11 => '收获成长比较',
                ];
                $data['summary_comparison'] = [
                    'title' => $summaryComparisonTitle[$synastryType] ?? '',
                    'list' => [
                        [
                            'nickname' => $newData[10]['name'] ?? '',
                            'score' => $newData[10]['score'] ?? 0,
                            'content' => $newData[10]['text'] ?? '',
                        ], [
                            'nickname' => $newData[11]['name'] ?? '',
                            'score' => $newData[11]['score'] ?? 0,
                            'content' => $newData[11]['text'] ?? '',
                        ],
                    ],
                ];
                // 相处建议
                $data['advice'] = sprintf("“ %s ”", $newData[15]['text'] ?? '');
                $ifLove = $newData[12]['text'] ?? '';
                if ($ifLove)
                {
                    $data['if_love'] = $ifLove;
                }
                if (isset($newData[13]))
                {   // 契合点
                    $data['foothold'] = $newData[13]['text'] ?? [];
                }
                if (isset($newData[14]))
                {   // 矛盾点
                    $data['conflict'] = $newData[14]['text'] ?? [];
                }
            }
            $data['prediction_info'] = [
                [
                    'score' => $newData[6]['score'] ?? 0,
                    'title' => $newData[6]['name'] ?? '',
                    'content' => $newData[6]['text'] ?? '',
                ], [
                    'score' => $newData[7]['score'] ?? 0,
                    'title' => $newData[7]['name'] ?? '',
                    'content' => $newData[7]['text'] ?? '',
                ], [
                    'score' => $newData[8]['score'] ?? 0,
                    'title' => $newData[8]['name'] ?? '',
                    'content' => $newData[8]['text'] ?? '',
                ], [
                    'score' => $newData[9]['score'] ?? 0,
                    'title' => $newData[9]['name'] ?? '',
                    'content' => $newData[9]['text'] ?? '',
                ],
            ];
            $scoreCommentTextCfg = [
                7 => "大众关系",
                8 => "恋爱关系",
                9 => "婚姻关系",
                10 => "事业关系",
                11 => "朋友关系",
            ];
            $totalScore = $data['score']['attract']['num'] +
                $data['score']['chat']['num'] +
                $data['score']['passion']['num'] +
                $data['score']['benefit']['num'] +
                $data['score']['happy']['num'] +
                $data['score']['probTobeLover']['num'];
            $resScore = $totalScore / 4.7;
            $scoreComment = ['当前分数超过了'];
            $scoreComment[] = sprintf("%d%%", min((int)$resScore, 98));
            $scoreComment[] = $scoreCommentTextCfg[$synastryType];
            if ($synastryType !== 7)
            {   // 非大众合盘
                $n = min((int)ceil($totalScore / 570 * 100), 95);
                $data['harmoniousAndConflict'] = [$n, 100 - $n];
            }
        }
        if ($saveData)
        {
            $score = 0;
            foreach ($data['score'] as $item)
            {
                $score += $item['num'];
            }
            $saveData['score'] = $score;// 总分
            $saveData['relation'] = $data['relation'][0]['name_cn']; // 双方可能的关系
            // 去写入
            $id = (new AppSynastryResult())->saveData($saveData, false);
        }
        if (in_array($synastryType, [8, 9, 10, 11], true))
        {
            $data['relation'] = [];
        }
        $data['nickname1'] = $recordDatas['recode1']['name'];
        $data['nickname2'] = $recordDatas['recode2']['name'];
        $data['avatar1'] = $recordDatas['recode1']['avatar'];
        $data['avatar2'] = $recordDatas['recode2']['avatar'];
        $data['rid1'] = (int)$rid1;
        $data['rid2'] = (int)$rid2;
        $data['type'] = in_array($sType, [2, 3, 5], true) ? 2 : 1; // 1显示合盘 2不显示   5=>名人合盘  6=>邀请好友合盘（不添加档案）
        $data['id'] = (int)$id;
        $data['synastry_type'] = $synastryType;
        if (in_array($synastryType, [2, 3, 5, 7]))
        {
            $data['score']['attract']['name'] = '吸引';
            $data['score']['benefit']['name'] = '亲密';
            $data['score']['chat']['name'] = '沟通';
            $data['score']['happy']['name'] = '愉悦';
            $data['score']['passion']['name'] = '激情';
            $data['score']['probTobeLover']['name'] = '缘分';

            if ($synastryType != 7)
            {
                $data['prediction_info'] = [];
            }
            $data['advice'] = '';
            $data['summary_comparison'] = null;
        }
        if (Util::IsHuawei() && !Util::huaweiIsShowAll())
        {
            $data['type'] = 2;
        }
        $oss = Env::get('host.photo');
        $btnList[] = [
            'name' => '详细解读',
            'target' => 'local',
            'link' => "synastry_result_explain?id={$id}&need_auth=1",
            'is_new' => 0,
            'icon' => $oss . '/test/synastry/synastry_explain.png',
            'tip_icon' => '',
        ];

        if ($data['type'] === 1 && !Util::AppIsPassShowV1())
        {   // 获取 合盘报告和AI 显隐开关 true=>显示 false=>隐藏
            $synastryReportSwitch = Util::getSynastryReportSwitch();
            if ($synastryReportSwitch)
            {   // 获取 当前合盘星盘两个档案是否已经解锁过相关关系
                $unlockStatus = (new ZlSynastryReport())->getUserHasReportUnlockStatus($this->user['id'], $data['rid1'], $data['rid2'], 1);
                $synastryReportNeedAuth = $this->user['young_model'] ? 3 : 1;
                if (in_array($synastryType, [2, 7, 8]))
                {
                    $btnList[] = [
                        'name' => '合盘报告',
                        'target' => 'local',
                        'link' => $unlockStatus ? "synastry_report_list?rid1={$rid1}&rid2={$rid2}&srid=1&need_auth={$synastryReportNeedAuth}" : "synastry_report_detail?rid1={$rid1}&rid2={$rid2}&srid=1&need_auth={$synastryReportNeedAuth}",
                        'is_new' => 1,
                        'icon' => $oss . '/test/synastry/synastry_report.png',
                        'tip_icon' => $oss . '/test/synastry/hot_icon.png',
                    ];
                }
                // H5邀请添加的，本地没有档案所以不展示AI对话解读
                if ($rid2)
                {
                    $btnList[] = [
                        'name' => 'AI对话解读',
                        'target' => 'local',
                        'link' => "aichat?type=0&rid={$rid1}&rid2={$rid2}&need_auth=0",
                        'icon' => $oss . '/test/synastry/synastry_ai.png',
                        'tip_icon' => '',
                    ];
                }
            }
        }
        $data['score_comment'] = $scoreComment;
        $data['btn_list'] = $btnList;
        if ($distinctId)
        {
            if ((!isset($record1) || empty($record1)) && $data['rid1'])
            {
                $record1 = $recodeModel->getInfoById($data['rid1']);
            } elseif (isset($result['rid1']))
            {
                $record1 = $recodeModel->getInfoById($result['rid1']);
            }
            if ((!isset($record2) || empty($record2)) && $data['rid2'])
            {
                $record2 = $recodeModel->getInfoById($data['rid2']);
            } elseif (isset($result['rid1']))
            {
                $record2 = [
                    'id' => $result['rid2'],
                    'name' => $result['nickname2'],
                    'isself' => 0,
                ];
            }
            $totalScore = $data['score']['attract']['num'] +
                $data['score']['chat']['num'] +
                $data['score']['passion']['num'] +
                $data['score']['benefit']['num'] +
                $data['score']['happy']['num'] +
                $data['score']['probTobeLover']['num'];
            $sensorsTrackData['synastry_score'] = $totalScore;
            $sensorsTrackData['record1_name'] = $data['nickname1'];
            $sensorsTrackData['record1_id'] = $data['rid1'];
            $sensorsTrackData['record2_name'] = $data['nickname2'];
            $sensorsTrackData['record2_id'] = $data['rid2'];
            $sensorsTrackData['has_self'] = ((int)$record1['isself'] === 1 || (int)$record2['isself'] === 1);
            SensorsData::track($uid, true, 'SynastryHandle', $sensorsTrackData);
        }
        return show(config('code.success'), '请求成功', $data);
    }
}
